package com.camus.algorithm.impl;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.camus.algorithm.SubsetAlgorithm4Int;

/**
 * 递归优化(数据有序的场景剪枝优化)算法求目标和的子集
 * 
 * @author jie.deng
 *
 */
public class SubsetAlgorithmOfSortPruningRecursion4Int2 implements SubsetAlgorithm4Int {
	
	private static final Logger log = LoggerFactory.getLogger(SubsetAlgorithmOfSortPruningRecursion4Int2.class);

	@Override
	public int[] findSubsetOfTargetSum(int[] candidateArr, int target) {
		counter.remove();
		// 先排序，方便后面有针对性地剪枝
		Arrays.sort(candidateArr);

		int len = candidateArr.length;
		// 前缀和
		int[] prefixSumArr = new int[len];
		prefixSumArr[0] = candidateArr[0];
		for (int i = 1; i < len; i++) {
			prefixSumArr[i] = prefixSumArr[i - 1] + candidateArr[i];
		}

		Deque<Integer> queue = new ArrayDeque<>();
		// 逐层递归
		int[] subsetArr = findSubsetOfTargetSum(candidateArr, 0, queue, target, prefixSumArr);
		log.info("入参paramArr={},target={},resultArr={},时间复杂度={}", Arrays.toString(candidateArr), target, subsetArr,
				counter.get());
		return subsetArr;
	}

	public int[] findSubsetOfTargetSum(int[] candidateArr, int candidateIdxBegin, Deque<Integer> selectedIdxQueue,
			int remain, int[] prefixSumArr) {
		counter.set(counter.get().intValue() + 1);
		int len = candidateArr.length;
		// 1.递归终止条件
		if (remain == 0) {
			return filterSubset(candidateArr, selectedIdxQueue);
		}
		if (candidateIdxBegin >= candidateArr.length) {
			return null;
		}

		// 2.当前层逻辑：可以在[candidateIdxBegin,len)中选择一个
		for (int i = candidateIdxBegin; i < len; i++) {
			if (i > candidateIdxBegin && candidateArr[i] == candidateArr[i - 1]) {
				// 剪枝
				continue;
			}
			if (failFast(candidateArr, i, remain, prefixSumArr)) {
				// 剪枝
				return null;
			}
			selectedIdxQueue.offerLast(i);

			// 3.递归调用下一层
			int[] arr = findSubsetOfTargetSum(candidateArr, i + 1, selectedIdxQueue, remain - candidateArr[i],
					prefixSumArr);
			if (arr != null) {
				return arr;
			}

			// 4.回溯
			selectedIdxQueue.pollLast();
		}
		return null;

	}

	private int[] filterSubset(int[] candidateArr, Deque<Integer> selectedIdxQueue) {
		int len = selectedIdxQueue.size();
		if (len == 0) {
			return null;
		}
		int[] subsetArr = new int[len];
		int idx = 0;
		while (!selectedIdxQueue.isEmpty()) {
			subsetArr[idx++] = candidateArr[selectedIdxQueue.pollFirst().intValue()];
		}
		return subsetArr;
	}

	/**
	 * 
	 * @param candidateArr      升序数组
	 * @param candidateIdxBegin 可选元素的索引的起始值
	 * @param target            目标和
	 * @param prefixSumArr      升序数组的前缀和
	 * @return 从[candidateIdxBegin, len)选择n个数是否可以凑出target，肯定凑不出则返回true
	 */
	private boolean failFast(int[] candidateArr, int candidateIdxBegin, int target, int[] prefixSumArr) {

		int len = candidateArr.length;
		if (candidateIdxBegin >= len) {
			return true;
		}
		int min = candidateArr[candidateIdxBegin];
		int max = candidateArr[len - 1];
		int sum = prefixSumArr[len - 1] - (candidateIdxBegin == 0 ? 0 : prefixSumArr[candidateIdxBegin - 1]);
		if (min >= 0) {
			// 所有元素都是正数
			if (min > target) {
				// 且最小元素大于目标和
				return true;
			}
			if (sum < target) {
				// 且所有元素之和仍然小于目标和
				return true;
			}
		}
		if (max <= 0) {
			// 所有元素都是负数，
			if (max < target) {
				// 且最大元素小于目标和
				return true;
			}
			if (sum > target) {
				// 且所有元素和仍然大于目标和
				return true;
			}
		}
		return false;
	}

}
